<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="所属阶段" prop="schoolType">
          <el-select
            v-model="queryParams.schoolType"
            clearable
            placeholder="所属阶段"
            class="!w-[100px]"
            @change="selectGradeType()"
          >
            <el-option
              v-for="option in options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属年级" prop="gradeInfoId">
          <el-select
            v-model="queryParams.gradeInfoId"
            clearable
            placeholder="所属年级"
            class="!w-[100px]"
            @change="selectSubjectType()"
          >
            <el-option
              v-for="option in optionsGrad"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属科目" prop="subjectId">
          <el-select
            v-model="queryParams.subjectId"
            clearable
            placeholder="所属科目"
            class="!w-[100px]"
          >
            <el-option
              v-for="option in optionsSub"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试题内容" prop="content">
          <el-input
            v-model="queryParams.content"
            placeholder="试题内容"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['exam:questioninfo:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          v-hasPerm="['exam:questioninfo:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
        <el-button
          v-hasPerm="['exam:questioninfo:import']"
          type="success"
          @click="importQuestion()"
        >
          <i-ep-UploadFilled />
          导入
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column key="id" label="主键" prop="id" min-width="100" /> -->
        <el-table-column label="试题内容" min-width="100">
          <template #default="scope">
            <div v-dompurify-html="scope.row.content"></div>
          </template>
        </el-table-column>
        <el-table-column
          key="subjectName"
          label="科目"
          prop="subjectName"
          min-width="100"
        />
        <el-table-column
          key="schoolTypeName"
          label="阶段"
          prop="schoolTypeName"
          min-width="100"
        />
        <el-table-column
          key="gradeName"
          label="年级"
          prop="gradeName"
          min-width="100"
        />
        <el-table-column
          key="questionTypeName"
          label="试题类型"
          prop="questionTypeName"
          min-width="100"
        />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="100"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['exam:questioninfo:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              v-hasPerm="['exam:questioninfo:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.current"
        v-model:limit="queryParams.size"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 试题信息表表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      size="100%"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="4">
            <el-form-item label="所属阶段:" prop="schoolType">
              <el-select
                v-model="formData.schoolType"
                clearable
                placeholder="所属阶段"
                class="!w-[200px]"
                @change="selectGradeType()"
              >
                <el-option
                  v-for="option in options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="所属年级:" prop="gradeInfoId">
              <el-select
                v-model="formData.gradeInfoId"
                clearable
                placeholder="所属年级"
                class="!w-[200px]"
                @change="selectSubjectType()"
              >
                <el-option
                  v-for="option in optionsGrad"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="所属科目:" prop="subjectId">
              <el-select
                v-model="formData.subjectId"
                clearable
                placeholder="所属科目"
                class="!w-[200px]"
              >
                <el-option
                  v-for="option in optionsSub"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="试题类型:" prop="questionType">
              <el-select
                v-model="formData.questionType"
                clearable
                placeholder="试题类型"
                class="!w-[200px]"
                @change="selectQuestionType()"
              >
                <el-option
                  v-for="option in optionsQuestion"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="题目:" prop="content">
          <div style="border: 1px solid #ccc">
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="formData.content"
            />
          </div>
        </el-form-item>
        <el-form-item label="试题解析:" prop="analysis">
          <div style="border: 1px solid #ccc">
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="formData.analysis"
            />
          </div>
        </el-form-item>
        <el-row>
          <el-col
            v-if="formData.questionType == 90 || formData.questionType == 91"
            :span="24"
          >
            <el-form-item
              v-for="(option, index) in optionList"
              :label="'选项' + option.label"
              :key="index"
            >
              <div class="option-container">
                <div
                  @click="openMathOptionsEditor(index)"
                  class="option-content"
                >
                  <span
                    v-dompurify-html="option.option_name || '点击编辑内容'"
                  ></span>
                </div>

                <div class="option-buttons">
                  <el-button
                    v-if="index === 0"
                    @click="addOption()"
                    type="warning"
                  >
                    添加选项
                  </el-button>
                  <el-button
                    v-else
                    type="danger"
                    @click="deleteOption(option.label, index)"
                  >
                    删除选项
                  </el-button>
                </div>
              </div>
            </el-form-item>

            <el-dialog
              :show-close="true"
              v-model="dialogFormVisible"
              style="width: 800px"
            >
              <Editor
                style="height: 800px; overflow-y: hidden"
                v-model="currentInputValue"
              />
              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="closedialog()">取 消</el-button>
                  <el-button @click="saveOptionValue" type="primary">
                    确 定
                  </el-button>
                </div>
              </template>
            </el-dialog>
          </el-col>
          <el-col :span="24">
            <el-form-item label="答案:" prop="answer">
              <!-- <template>
                <script id="answerEditor" type="text/plain"></script>
              </template> -->
              <template
                v-if="
                  formData.questionType !== 90 &&
                  formData.questionType !== 91 &&
                  formData.questionType !== 95
                "
              >
                <div style="border: 1px solid #ccc">
                  <Editor
                    style="height: 800px; overflow-y: hidden"
                    v-model="formData.answer"
                  />
                </div>
              </template>
              <!--- 显示单选题答案选项 -->
              <template v-if="formData.questionType === 90">
                <el-radio-group v-model="formData.answer">
                  <el-radio
                    :key="index"
                    v-for="(option, index) in radioOptionList"
                    :label="option"
                  >
                    {{ option }}
                  </el-radio>
                </el-radio-group>
              </template>

              <template v-if="formData.questionType === 91">
                <el-checkbox-group v-model="answerList">
                  <el-checkbox
                    :key="index"
                    v-for="(option, index) in checkBoxOptionList"
                    :label="option"
                  />
                </el-checkbox-group>
              </template>

              <template v-if="formData.questionType === 95">
                <el-radio-group v-model="formData.answer">
                  <el-radio :label="'1'">对</el-radio>
                  <el-radio :label="'0'">错</el-radio>
                </el-radio-group>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </div>
      </template>
    </el-drawer>

    <el-dialog v-model="dialogImportFormVisible" title="试题导入" width="500">
      <!-- <el-card class="box-card"> -->
      <div>
        <label style="font-size: 20px; font-weight: bold">1.下载模板</label>
        <label style="margin-left: 40px; color: #a8a8a8">
          下载需要导入试题所用的模板
        </label>
      </div>

      <div style="margin: 10px">
        <el-button @click="dowLoadQuestionExcel()" type="text">
          下载Excel模版
        </el-button>
        <el-button @click="dowLoadQuestionTxt()" type="text">
          下载TxT模版
        </el-button>
      </div>

      <div>
        <label style="font-size: 20px; font-weight: bold">2.试题导入</label>
      </div>
      <div style="margin: 20px">
        <el-form
          ref="dataImportFormRef"
          :model="importFormData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="所属阶段:" prop="schoolType">
            <el-select
              v-model="importFormData.schoolType"
              clearable
              placeholder="所属阶段"
              class="!w-[200px]"
              @change="selectGradeType()"
            >
              <el-option
                v-for="option in options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属年级:" prop="gradeInfoId">
            <el-select
              v-model="importFormData.gradeInfoId"
              clearable
              placeholder="所属年级"
              class="!w-[200px]"
              @change="selectSubjectType()"
            >
              <el-option
                v-for="option in optionsGrad"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属科目:" prop="subjectId">
            <el-select
              v-model="importFormData.subjectId"
              clearable
              placeholder="所属科目"
              class="!w-[200px]"
            >
              <el-option
                v-for="option in optionsSub"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文件:">
            <!-- :headers="headers" -->
            <el-upload
              :with-credentials="true"
              class="upload-demo"
              :data="importFormData.file"
              :show-file-list="true"
              :on-success="uploadExcelSuccess"
              :before-upload="beforeUploadExcel"
            >
              <el-button type="primary">导入试题</el-button>
              <template #tip>
                <div v-if="importFormData.file">
                  {{ importFormData.file.name }}
                </div>
                <div class="el-upload__tip">只能上传excel/txt文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeImportDialog()">取 消</el-button>
          <el-button @click="saveImportData()" type="primary">确 定</el-button>
        </div>
      </template>
      <!-- </el-card> -->
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "QuestionInfo",
  inheritAttrs: false,
});

import QuestionInfoAPI, {
  QuestionInfoForm,
  QuestionInfoPageQuery,
  QuestionInfoPageVO,
  QuestionInfoImportForm,
} from "@/api/question_info";
import DictAPI from "@/api/dict";
import GradeInfoAPI, { GradeInfoPageVO } from "@/api/grade_info";
import SubjectInfoAPI, { SubjectInfoPageVO } from "@/api/subject_info";
import Editor from "@/components/WangEditor/index.vue";
const queryFormRef = ref<ElForm>();
const dataFormRef = ref<ElForm>();
const dataImportFormRef = ref<ElForm>();

const loading = ref(false);
const importLoading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);
const options: Ref<OptionType[]> = ref([]);
const optionsGrad: Ref<GradeInfoPageVO[]> = ref([]);
const optionsSub: Ref<SubjectInfoPageVO[]> = ref([]);
const optionsQuestion: Ref<OptionType[]> = ref([]);
let dialogFormVisible = ref(false);
let dialogImportFormVisible = ref(false);
let optionList = ref([]);
let radioOptionList = ref<string[]>([]);
let checkBoxOptionList = ref<string[]>([]);
let answerList = ref([]);
const currentInputIndex = ref(-1);
const currentInputValue = ref("");
const autocompleteKey = ref(0);

const queryParams = reactive<QuestionInfoPageQuery>({
  current: 1,
  size: 10,
});

// 试题信息表表格数据
const pageData = ref<QuestionInfoPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 试题信息表表单数据
const formData = reactive<QuestionInfoForm>({});

// 试题信息表表单数据
const importFormData = reactive<QuestionInfoImportForm>({});

// 试题信息表表单校验则
const rules = reactive({});

/** 查询试题信息表 */
function handleQuery() {
  loading.value = true;
  queryParams.bs = "all";
  QuestionInfoAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置试题信息表查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开试题信息表弹窗 */
function handleOpenDialog(id?: number) {
  selectGradeType();
  selectSubjectType();
  dialog.visible = true;
  if (id) {
    dialog.title = "修改试题信息表";
    QuestionInfoAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
      optionList.value = JSON.parse(formData.options);
      radioOptionList.value = [];
      checkBoxOptionList.value = [];
      if (formData.questionType === 90 || formData.questionType === 91) {
        // 初始化答案选项
        for (let i = 0; i < optionList.value.length; i++) {
          let label = String.fromCharCode("A".charCodeAt() + i);
          radioOptionList.value.push(label);
          checkBoxOptionList.value.push(label);
        }
        // 处理多选题答案
        if (formData.questionType === 91) {
          if (formData.answer) {
            formData.answer.split(",").forEach((item) => {
              if (item) {
                answerList.value.push(item);
              }
            });
          }
        }
      }
    });
  } else {
    dialog.title = "新增试题信息表";
  }
}

/** 提交试题信息表表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        QuestionInfoAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        QuestionInfoAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭试题信息表弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除试题信息表 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      QuestionInfoAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

function selectGradeType() {
  // 根据字典id获取年级管理列表
  GradeInfoAPI.getList(queryParams).then((data) => {
    optionsGrad.value = data;
  });
}

function selectSubjectType() {
  SubjectInfoAPI.getList(queryParams).then((data) => {
    optionsSub.value = data;
  });
}

function openMathOptionsEditor(index: any) {
  autocompleteKey.value = autocompleteKey.value + 1;
  dialogFormVisible.value = true;
  currentInputIndex.value = index;
  currentInputValue.value = optionList.value[index].option_name;
}

function addOption() {
  let label = String.fromCharCode(65 + optionList.value.length); // 使用65作为'A'的ASCII码
  optionList.value.push({
    label: label,
    option_name: "", // 初始化为空字符串
  });

  // 单选题
  if (formData.questionType === 90) {
    radioOptionList.value.push(label);
    // 多选题
  } else if (formData.questionType === 91) {
    checkBoxOptionList.value.push(label);
  }
}

function deleteOption(label: string, index: number) {
  optionList.value.splice(index, 1);
  if (formData.questionType === 90) {
    radioOptionList.value.splice(index, 1);
  } else {
    checkBoxOptionList.value.splice(index, 1);
  }
}

function selectQuestionType() {
  if (formData.questionType === 90 || formData.questionType === 91) {
    optionList.value = [];
    optionList.value.push({
      label: "A",
      option_name: "",
    });

    if (formData.questionType === 90) {
      radioOptionList.value = [];
      radioOptionList.value.push("A");
    } else if (formData.questionType === 91) {
      checkBoxOptionList.value = [];
      checkBoxOptionList.value.push("A");
    }
  }
  // answerEditor.setHide(true);
}

function saveOptionValue() {
  if (currentInputIndex.value !== -1) {
    optionList.value[currentInputIndex.value].option_name =
      currentInputValue.value;
  }
  dialogFormVisible.value = false;
}
function closedialog() {
  dialogFormVisible.value = false;
}

//导入试题
function importQuestion() {
  dialogImportFormVisible.value = true;
}

function closeImportDialog() {
  dialogImportFormVisible.value = false;
  dataImportFormRef.value.resetFields();
  dataImportFormRef.value.clearValidate();
  importFormData.file = undefined;
}

function saveImportData() {
  QuestionInfoAPI.uploadQuestion(importFormData)
    .then(() => {
      ElMessage.success("导入成功");
      closeImportDialog();
      handleResetQuery();
    })
    .catch((error) => {
      ElMessage.error("导入失败: " + error.message);
    });
}

function dowLoadQuestionExcel() {
  QuestionInfoAPI.downloadExcel().then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

function dowLoadQuestionTxt() {
  QuestionInfoAPI.downloadTxt().then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType = "text/plain;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

//上传前校验接口
function beforeUploadExcel(file: File) {
  if (!importFormData.gradeInfoId) {
    ElMessage.error("请选择年级");
    return false;
  }

  if (!importFormData.subjectId) {
    ElMessage.error("请选择科目");
    return false;
  }

  importLoading.value = true;

  importFormData.file = file;
  return false; // 阻止默认的上传行为
}
//上传成功的口
function uploadExcelSuccess(res: any) {
  // 这里可以处理上传成功的逻辑
  ElMessage.success("文件上传成功");
  importLoading.value = false;
}

onMounted(() => {
  // 根据字典编码获取字典项
  DictAPI.getOptions("SSJD").then((data) => {
    options.value = data;
  });

  // 根据字典编码获取字典项
  DictAPI.getOptions("STLX").then((data) => {
    optionsQuestion.value = data;
  });

  handleQuery();
});
</script>

<style scoped>
.option-container {
  display: flex;
  gap: 10px;
  align-items: center;
  width: 100%;
  margin-bottom: 10px;
}

.option-content {
  display: flex;
  align-items: center;
  width: 300px;
  height: 32px;
  padding: 0 12px;
  cursor: pointer;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.option-content:hover {
  border-color: #409eff;
}

.option-buttons {
  display: flex;
  gap: 8px;
}

/* 调整表单项的样式 */
:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
</style>
